import { Directive, DirectiveBinding } from "vue";
interface LoadingElement extends HTMLElement {
  _loadingInstance?: {
    loading: boolean;
    originalHandler: Function;
    loadingElement?: HTMLElement;
  };
}
/**
 * 全局按钮loading指令
 * 使用方式：v-global-loading="handleFunction"
 * 或者：v-global-loading="{ handler: handleFunction, text: '加载中' }"
 */
const globalBtnLoading: Directive = {
  mounted(el: LoadingElement, binding: DirectiveBinding) {
    // 保存原始点击处理函数
    const value = binding.value;
    const handler = typeof value === 'function' ? value : value.handler;
    const loadingText = typeof value === 'object' && value.text ? value.text : '配置中';  
    if (typeof handler !== 'function') {
      console.warn('v-global-loading指令需要一个函数作为参数');
      return;
    }
    // 存储原始处理函数和loading状态
    el._loadingInstance = {
      loading: false,
      originalHandler: handler
    };

    // 创建loading元素
    const loadingElement = document.createElement('div');
    loadingElement.className = 'global-btn-loading-effect';
    loadingElement.innerHTML = `
      <div class="loading-spinner">
        <div class="spinner-ring"></div>
        <div class="spinner-ring"></div>
        <div class="spinner-dot"></div>
      </div>
      <span class="loading-text">${loadingText}</span>
    `;
    loadingElement.style.display = 'none';
    el.appendChild(loadingElement);
    el._loadingInstance.loadingElement = loadingElement;

    // 替换原始点击处理函数
    el.addEventListener('click', async function(event) {
      if (el._loadingInstance?.loading) {
        event.preventDefault();
        event.stopPropagation();
        return;
      }

      // 设置loading状态
      el._loadingInstance!.loading = true;
      el.classList.add('is-loading');
      if (el._loadingInstance?.loadingElement) {
        el._loadingInstance.loadingElement.style.display = 'flex';
      }

      try {
        // 执行原始处理函数，支持异步
        const result = handler(event);
        if (result instanceof Promise) {
          await result;
        }
      } finally {
      
        // 无论成功失败，都恢复非loading状态
        el._loadingInstance!.loading = false;
        el.classList.remove('is-loading');
        if (el._loadingInstance?.loadingElement) {
          el._loadingInstance.loadingElement.style.display = 'none';
        }
      }
    });
  },
  
  beforeUnmount(el: LoadingElement) {
    // 清理资源
    if (el._loadingInstance?.loadingElement) {
      el.removeChild(el._loadingInstance.loadingElement);
    }
    delete el._loadingInstance;
  },
  
  updated(el: LoadingElement, binding: DirectiveBinding) {
    // 更新处理函数
    if (el._loadingInstance) {
      const value = binding.value;
      const handler = typeof value === 'function' ? value : value.handler;
      
      if (typeof handler === 'function') {
        el._loadingInstance.originalHandler = handler;
      }
      
      // 更新loading文本
      if (typeof value === 'object' && value.text && el._loadingInstance.loadingElement) {
        const textElement = el._loadingInstance.loadingElement.querySelector('.loading-text');
        if (textElement) {
          textElement.textContent = value.text;
        }
      }
    }
  }
};

export default globalBtnLoading;